package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.core.Result;
import com.dongdongshop.core.ResultEnum;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.CartService;
import com.dongdongshop.util.CookieUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("cartController")
public class CartController {
    //开启日志
    Logger logger = LoggerFactory.getLogger(CartController.class);

    @Reference(check=false ,timeout=106666)
    private CartService cartService;

    //1、用户未登录
    //2、用户已登录

    @RequestMapping("cartList")
    public String cartList(HttpServletRequest request, HttpServletResponse response, Model model){
        //获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        List<Cart> cartList = getCart(request, response);
        model.addAttribute("cartList",cartList);
        model.addAttribute("user",user);
        return "cart";
    }


    //操作cookie，web项目，负责前后台之间的数据交互
    //获取购物车信息
    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request, HttpServletResponse response){
        //从cookie中获取购物车
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();

        String cartListValue = CookieUtils.getCookieValue(request, "cartList", "UTF-8");
        if (cartListValue == null || cartListValue.equals("")){
            cartListValue = "[]";
        }
            /*Optional<String> optional = Optional.ofNullable(cartListValue);
            cartListValue = optional.orElse("[]");*/
        //将cookie中的数据转成list
        List<Cart> cartsCookie = JSONObject.parseArray(cartListValue, Cart.class);
        //判断用户是否登录
        if (user == null){
            return cartsCookie;
        }else {//登录
            List<Cart> cartsRedis =  cartService.findCartListFromRedis(user.getUsername());
            if (cartsCookie.size() > 0){
                //合并购物车
                List<Cart> mergeList = cartService.mergeCarList(cartsCookie,cartsRedis);
                //将合并后的购物车存到Redis
                cartService.addToCartRedis(mergeList,user.getUsername());
                //删除本地的cookie
                CookieUtils.deleteCookie(request,response,"cartList");
                return mergeList;
            }

            return cartsRedis;
        }
    }
    //往购物车中添加数据
    @RequestMapping("addToCart")
    /*@ResponseBody*/
    public String addToCart(HttpServletRequest request, HttpServletResponse response,Long itemId,Integer num,Model model){

        //1、从cookie中获取购物车列表
        List<Cart> cartList = getCart(request, response);
        //调用cartservice组装购物车
        cartList = cartService.addToCart(cartList,itemId,num);
        //获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            //3、将组装好的购物车写入cookie中
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),60*60*24*30,"UTF-8");
        }else {
            cartService.addToCartRedis(cartList,user.getUsername());
        }
        //Result.response(ResultEnum.SUCCESS).setData(cartList)
        model.addAttribute("itemId",itemId);
        model.addAttribute("num",num);
        model.addAttribute("user",user);
        return "success-cart";

    }

    //删除
    @RequestMapping("delCartOrderByItemId")
    @ResponseBody
    public Result delCartOrderByItemId(HttpServletRequest request,HttpServletResponse response,Long itemId, Integer num){

        //1、从cookie中获取购物车列表
        List<Cart> cartList = getCart(request, response);
        //调用cartservice组装购物车
        cartList = cartService.addToCart(cartList,itemId,num);
        //获取登录用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            //3、将组装好的购物车写入cookie中
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),60*60*24*30,"UTF-8");
        }else {
            cartService.addToCartRedis(cartList,user.getUsername());
        }
        return Result.response(ResultEnum.SUCCESS);
    }

    //跳转购物车结算页
    @RequestMapping("getOrderInfoList")
    public String getOrderInfoList(HttpServletRequest request, HttpServletResponse response, Model model){
        List<Cart> cartList = getCart(request, response);
        model.addAttribute("cartList",cartList);

        return "getOrderInfo";
    }


}
